﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EnvDTE;
using Liberate.CodeGenerator;
using Liberate.VSIntergration.Errors;

namespace Liberate.VSIntergration.Commands
{
    public partial class GenerateFileDialog : Form
    {
        public const string LVMTemplateExtension = ".lbTemplate";

        public string ConfigFile { get; set; }
        public TemplateConfig TemplateConfig { get; set; }

        public GenerateFileDialog()
        {
            InitializeComponent();
            templateView.SmallImageList = new ImageList { ImageSize = new Size(16, 16) };
            templateView.LargeImageList = new ImageList { ImageSize = new Size(32, 32) };
            cmbViewType.SelectedIndex = 0;
            templateView.SmallImageList.Images.Add(Resources.DefaultIcon);
            templateView.LargeImageList.Images.Add(Resources.DefaultIcon);
        }

        protected override void OnLoad(EventArgs e)
        {
            var templatesFolder = DTEHelper.GetTemplatesFolder();
            if (templatesFolder != null)
            {
                BuildCategoryTree(templatesFolder, categoryTree.Nodes);
                if (categoryTree.Nodes.Count > 0)
                {
                    categoryTree.SelectedNode = categoryTree.Nodes[0];
                }
                categoryTree.ExpandAll();
            }
            base.OnLoad(e);
        }

        private void BuildCategoryTree(ProjectItem folder, TreeNodeCollection nodes)
        {
            foreach (ProjectItem item in folder.ProjectItems)
            {
                if (item.IsFolder())
                {
                    //item is a folder
                    var node = new TreeNode(item.Name) { Tag = item };
                    nodes.Add(node);
                    BuildCategoryTree(item, node.Nodes);
                }
            }
        }



        private void btnGenerate_Click(object sender, EventArgs e)
        {
            var item = templateView.SelectedItems != null && templateView.SelectedItems.Count > 0
                           ? templateView.SelectedItems[0]
                           : null;
            if (item == null)
            {
                MessageBox.Show("请选择一个模板");
                return;
            }

            object[] arr = item.Tag as object[];
            if (arr == null || arr.Length != 2) return;
            var projectItem = arr[0] as ProjectItem;
            if (projectItem == null) return;

            var cfg = arr[1] as TemplateConfig;
            if (cfg == null) return;

            ConfigFile = projectItem.get_FileNames(1);
            TemplateConfig = cfg;
            DialogResult = DialogResult.OK;
            Close();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        private void categoryTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node == null) return;
            templateView.Items.Clear();
            var items = e.Node.Tag as List<ListViewItem>;
            if (items != null)
            {
                //fill items from cache
                foreach (var item in items)
                {
                    item.Group = templateView.Groups[0];
                    templateView.Items.Add(item);
                }
            }
            else
            {
                var folder = e.Node.Tag as ProjectItem;
                if (folder == null || folder.ProjectItems == null) return;
                BindListItems(folder);
                //cache items
                var cachedItems = new List<ListViewItem>();
                foreach (ListViewItem item in templateView.Items)
                {
                    cachedItems.Add(item);
                }
                e.Node.Tag = cachedItems;
            }
        }

        private void BindListItems(ProjectItem folder)
        {
            foreach (ProjectItem item in folder.ProjectItems)
            {
                if (item.IsFile())
                {
                    var ext = Path.GetExtension(item.Name);
                    if (LVMTemplateExtension.Equals(ext, StringComparison.OrdinalIgnoreCase))
                    {
                        var listItem = CreateListItem(item);
                        if (listItem != null)
                        {
                            templateView.Items.Add(listItem);
                        }
                    }
                }
            }
        }

        private ListViewItem CreateListItem(ProjectItem item)
        {
            var fileName = item.get_FileNames(1);
            try
            {
                var cfg = TemplateConfigLoader.Load(fileName);
                if (cfg != null)
                {
                    var listItem = new ListViewItem(cfg.Name ?? item.Name) { Group = templateView.Groups[0], Tag = new object[] { item, cfg } };
                    if (!string.IsNullOrEmpty(cfg.Icon))
                    {
                        var dir = Path.GetDirectoryName(fileName);
                        var iconPath = Path.Combine(dir, cfg.Icon);
                        try
                        {
                            Image icon = Image.FromFile(iconPath);
                            templateView.SmallImageList.Images.Add(icon);
                            templateView.LargeImageList.Images.Add(icon);
                            listItem.ImageIndex = templateView.SmallImageList.Images.Count - 1;
                        }
                        catch (Exception ex)
                        {
                            listItem.ImageIndex = 0;
                            ErrorHandler.ShowErrors(false, ex);
                        }
                    }
                    else
                    {
                        listItem.ImageIndex = 0;
                    }
                    return listItem;
                }
            }
            catch (Exception ex)
            {
                ErrorHandler.ShowErrors(false, ex);
            }
            return null;
        }

        private void cmbViewType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cmbViewType.SelectedIndex == 0)
            {
                templateView.View = View.LargeIcon;
            }
            else
            {
                templateView.View = View.SmallIcon;
            }
        }

        private void templateView_SelectedIndexChanged(object sender, EventArgs e)
        {
            var item = templateView.SelectedItems != null && templateView.SelectedItems.Count > 0
                           ? templateView.SelectedItems[0]
                           : null;
            if (item == null) return;
            object[] arr = item.Tag as object[];
            if (arr == null || arr.Length != 2) return;
            var cfg = arr[1] as TemplateConfig;
            if (cfg == null) return;

            txtDescription.Text = cfg.Description;
        }
    }
}
